package com.fxp.project.jiuselu.web.models.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fxp.project.jiuselu.commons.constant.ConstantCode;
import com.fxp.project.jiuselu.commons.exceptions.JiuLuException;
import com.fxp.project.jiuselu.commons.exceptions.ParamException;
import com.fxp.project.jiuselu.commons.name.Language;
import com.fxp.project.jiuselu.commons.name.RandomNameTool;
import com.fxp.project.jiuselu.commons.rsa.RsaUtil;
import com.fxp.project.jiuselu.commons.utils.CommonUtil;
import com.fxp.project.jiuselu.web.base.controller.BaseController;
import com.fxp.project.jiuselu.web.business.v1.pojo.*;
import com.fxp.project.jiuselu.web.business.v1.request.user.ChangePwdByPhone;
import com.fxp.project.jiuselu.web.business.v1.request.user.ChangePwdByPwd;
import com.fxp.project.jiuselu.web.business.v1.request.user.CustomManagerByUserId;
import com.fxp.project.jiuselu.web.business.v1.request.user.SetInviteUse;
import com.fxp.project.jiuselu.web.config.CustomerApiConfig;
import com.fxp.project.jiuselu.web.models.commission.entity.JslCommissionRation;
import com.fxp.project.jiuselu.web.models.commission.mapper.JslCommissionMapper;
import com.fxp.project.jiuselu.web.models.common.entity.JslBackendConfig;
import com.fxp.project.jiuselu.web.models.common.mapper.JslBackendConfigMapper;
import com.fxp.project.jiuselu.web.models.common.vo.CommissionVo;
import com.fxp.project.jiuselu.web.models.coupon.entity.JslCoupon;
import com.fxp.project.jiuselu.web.models.coupon.entity.JslUserCoupon;
import com.fxp.project.jiuselu.web.models.coupon.mapper.JslCouponMapper;
import com.fxp.project.jiuselu.web.models.coupon.mapper.JslUserCouponMapper;
import com.fxp.project.jiuselu.web.models.order.entity.JslOrderGoods;
import com.fxp.project.jiuselu.web.models.order.entity.JslUserBalance;
import com.fxp.project.jiuselu.web.models.order.mapper.JslOrderGoodsMapper;
import com.fxp.project.jiuselu.web.models.order.mapper.JslOrderMapper;
import com.fxp.project.jiuselu.web.models.order.mapper.JslUserBalanceMapper;
import com.fxp.project.jiuselu.web.models.order.service.IJslOrderService;
import com.fxp.project.jiuselu.web.models.order.service.IJslUserBalanceService;
import com.fxp.project.jiuselu.web.models.order.vo.JslOrderVo;
import com.fxp.project.jiuselu.web.models.order.vo.JslUserOrderTotalVo;
import com.fxp.project.jiuselu.web.models.shareprofit.entity.JslShareProfitRecord;
import com.fxp.project.jiuselu.web.models.shareprofit.mapper.JslShareProfitRecordMapper;
import com.fxp.project.jiuselu.web.models.shareprofit.vo.JslShareProfitRecordVo;
import com.fxp.project.jiuselu.web.models.shareprofit.vo.StatisticUserProfitMoneyVo;
import com.fxp.project.jiuselu.web.models.user.entity.JslSaleInfo;
import com.fxp.project.jiuselu.web.models.user.entity.JslUser;
import com.fxp.project.jiuselu.web.models.user.mapper.JslSaleInfoMapper;
import com.fxp.project.jiuselu.web.models.user.mapper.JslUserMapper;
import com.fxp.project.jiuselu.web.models.user.request.ReqLogin;
import com.fxp.project.jiuselu.web.models.user.service.IJslUserService;
import com.fxp.project.jiuselu.web.models.user.vo.CommissionManagerInfoVo;
import com.fxp.project.jiuselu.web.models.user.vo.JslUserSaleInfoVo;
import com.fxp.project.jiuselu.web.models.userbank.service.IJslUserBankCardInfoService;
import com.fxp.project.jiuselu.web.models.userbank.vo.BankCardInfoVo;
import com.fxp.project.jiuselu.web.security.userdetails.CustomerUserDetails;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author Jason.Wang
 * @since 2021-11-01
 */
@Service
public class JslUserServiceImpl extends ServiceImpl<JslUserMapper, JslUser> implements IJslUserService {
    @Autowired
    JslUserMapper jslUserMapper;
    @Autowired
    JslSaleInfoMapper jslSaleInfoMapper;
    @Autowired
    PasswordEncoder passwordEncoder;
    @Autowired
    private JslBackendConfigMapper jslBackendConfigMapper;
    @Autowired
    private JslShareProfitRecordMapper jslShareProfitRecordMapper;
    @Autowired
    private JslOrderMapper jslOrderMapper;

    @Autowired
    private CustomerApiConfig customerApiConfig;

    @Autowired
    private IJslUserBankCardInfoService iJslUserBankCardInfoService;

    @Resource
    private IJslUserBalanceService jslUserBalanceService;

    @Resource
    private JslOrderGoodsMapper jslOrderGoodsMapper;

    @Resource
    private IJslOrderService jslOrderService;

    @Resource
    private JslUserCouponMapper jslUserCouponMapper;

    @Resource
    private JslCouponMapper jslCouponMapper;

    @Resource
    private JslCommissionMapper commissionMapper;

    @Resource
    private JslUserBalanceMapper jslUserBalanceMapper;

    private Lock lock=new ReentrantLock();

    //商品除去运费手续费税点的金额
    public BigDecimal sum(List<JslOrderGoods> jslOrderGoods,String orderId){
        //基本金额
        BigDecimal result = new BigDecimal("0");
        for (JslOrderGoods vo : jslOrderGoods) {
            BigDecimal multiply = new BigDecimal(vo.getGoodsNum()).multiply(vo.getAttrWeight()).multiply(vo.getGoodsPrice());
            result = result.add(multiply);
        }
        //判断是否使用了优惠卷
        JslUserCoupon jslUserCoupon = jslUserCouponMapper.selectOne(new QueryWrapper<JslUserCoupon>().lambda().eq(JslUserCoupon::getOrderId, orderId));
        JslOrderVo jslOrderVo = jslOrderMapper.selectJslOrderVoByOrderId(orderId);
        if (jslUserCoupon!=null){
            JslCoupon jslCoupon = jslCouponMapper.selectById(jslUserCoupon.getCouponId());
            if (jslCoupon!=null){
                switch (jslCoupon.getCategory()){
                    //优惠价
                    case 0:
                        BigDecimal discount = jslCoupon.getDiscount();
                        result=result.subtract(discount);
                        break;
                    //代金卷
                    case 1:
//                        BigDecimal discount1 = jslCoupon.getDiscount();
//                        result=result.multiply(new BigDecimal("100").subtract(discount1)).multiply(new BigDecimal("0.01"));
                        result=result.subtract(jslOrderVo.getCouponPrice());
                        if(result.compareTo(new BigDecimal(0.00)) < 0){
                            result=new BigDecimal(0.00);
                        }
                        break;
                }
            }
        }
        return result;
    }

    /**
     * 分润计算并存储历史就
     *
     * @param orderId  当前订单id
     * @param userId   当前交易用户userId
     * @param totalPay 当前交易总金额
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void calculateProfit(String orderId, Long userId, BigDecimal totalPay) {
        //查询 所有分润的比例    inc_type = 'share_profit' 为分润比例的type  key 为 【share_profit_level_0、1、2】 对应的当前级别的(普通员工、业务员、经理) 的分润比例 value 为比例数值 直接乘
        List<JslBackendConfig> shareProfitList = jslBackendConfigMapper.selectByIncType("share_profit");

        CommissionVo one = jslBackendConfigMapper.findOne();
//        orderId=orderId.substring(0,orderId.length()-1);
        JslOrderVo jslOrderVo = jslOrderService.selectJslOrderVoByUserIdAndOrderId(orderId, userId);
        //商品除去运费手续费税点的金额
        totalPay=sum(jslOrderVo.getOrderGoodsList(),orderId);

        if (null != shareProfitList && shareProfitList.size() > 0) {

//            Map<String, JslBackendConfig> map = shareProfitList.stream().collect(Collectors.toMap(JslBackendConfig::getName, JslBackendConfig -> JslBackendConfig));
            //计算第一级别 客户
            JslUser jslUser = jslUserMapper.selectById(userId);
            if (null != jslUser.getInviteId()) {
                List<JslShareProfitRecord> recordList = new ArrayList<>();
                JslUser jslUserLevel1 = jslUserMapper.selectById(jslUser.getInviteId());
//                JslBackendConfig jslBackendConfig = map.get("share_profit_level_" + jslUserLevel1.getLevel());
                BigDecimal profitLevel1 = totalPay.multiply(one.getCustomer()).multiply(new BigDecimal("0.01"));
                //新建 分润记录便  记录字段 当前订单id  当前分润比例  用户id
                recordList.add(new JslShareProfitRecord(orderId, profitLevel1, jslUserLevel1.getUserId(),userId,2));
                //更新一级分润  用户userid  更新用户当前金额 userMoney   distributeMoney 增加当前佣金
                jslUserMapper.updateShareProfit(jslUserLevel1.getUserId(), jslUserLevel1.getUserMoney().add(profitLevel1), jslUserLevel1.getDistributeMoney().add(profitLevel1));
                //计算二级利润
                if (null != jslUserLevel1.getInviteId()) {
                    //通过一级上级查出其二级上级
                    JslUser jslUserLevel2 = jslUserMapper.selectById(jslUserLevel1.getInviteId());
                    //获取分润比例
//                    JslBackendConfig jslBackendConfigLevel2 = map.get("share_profit_level_" + jslUserLevel2.getLevel());
                    //这里需要判断是上一级分润来计算 还是总金额来计算 这里有待确定后修改
                    BigDecimal profitLevel2 = totalPay.multiply(one.getFirst()).multiply(new BigDecimal("0.01"));
                    recordList.add(new JslShareProfitRecord(orderId, profitLevel2, jslUserLevel2.getUserId(),userId,1,jslUserLevel1.getUserId()));
                    System.out.println(jslUserLevel2.getUserId()+"------------");
                    System.out.println(jslUserLevel2.getUserMoney().add(profitLevel2)+"22222222222222222222222");
                    System.out.println(jslUserLevel2.getDistributeMoney().add(profitLevel2)+"333333333333333333333");
                    jslUserMapper.updateShareProfit(jslUserLevel2.getUserId(), jslUserLevel2.getUserMoney().add(profitLevel2), jslUserLevel2.getDistributeMoney().add(profitLevel2));


                    if (null!=jslUserLevel2.getInviteId()){
                        JslUser jslUserLevel3 = jslUserMapper.selectById(jslUserLevel2.getInviteId());
                        if(jslUserLevel3!=null){
                            BigDecimal profitLevel3 = totalPay.multiply(one.getSecond()).multiply(new BigDecimal("0.01"));
                            recordList.add(new JslShareProfitRecord(orderId, profitLevel3, jslUserLevel3.getUserId(),userId,0,jslUserLevel1.getUserId(),jslUserLevel2.getUserId()));
                            jslUserMapper.updateShareProfit(jslUserLevel3.getUserId(), jslUserLevel3.getUserMoney().add(profitLevel3), jslUserLevel3.getDistributeMoney().add(profitLevel3));
                        }
                    }
                }

                for (JslShareProfitRecord e : recordList) {
                    List<JslShareProfitRecord> list = jslShareProfitRecordMapper.selectList(new QueryWrapper<JslShareProfitRecord>().lambda().eq(JslShareProfitRecord::getOrderId, e.getOrderId()).eq(JslShareProfitRecord::getUserId, e.getUserId()));
                    if (list.size()==0){
                        jslShareProfitRecordMapper.insert(e);
                        //创建佣金余额明细
                        switch (e.getLevel()){
                            case 0:
                                jslUserBalanceService.addBalance(2,e.getProfitMoney(),e.getOrderId(),e.getUserId(),e.getThrCreate());
                                break;
                            case 1:
                                jslUserBalanceService.addBalance(2,e.getProfitMoney(),e.getOrderId(),e.getUserId(),e.getTwoCreate());
                                break;
                            case 2:
                                jslUserBalanceService.addBalance(1,e.getProfitMoney(),e.getOrderId(),e.getUserId(),e.getCreateUser());
                                break;
                        }
                    }
                }
            }
        }
    }

    /**
     * getUserInfoVoByUserId: 通过用户的Id获取当前用户的信息<br/>
     *
     * @param userId
     * @return
     * @author Kai.Wang
     * @date 2021/11/1 14:21
     */
    @Override
    public UserInfoVo getUserInfoVoByUserId(Long userId) {
        return jslUserMapper.getUserInfoVoByUserId(userId);
    }

    @Override
    public InviteUserInfoVo getUserByInviteCode(String inviteCode) {
        return jslUserMapper.selectUserByInviteCode(inviteCode);
    }

    /**
     * saveUser: 添加注册用户信息<br/>
     *
     * @param reqLogin
     * @return
     * @author Kai.Wang
     * @date 2021/11/1 14:28
     */
    @Override
    @Transactional(readOnly = false, rollbackFor = {Exception.class})
    public boolean saveUser(ReqLogin reqLogin) {
        JslUser inviteUser = null;
        // 查询当前的邀请码对应的用户信息
        if (StringUtils.isNotBlank(reqLogin.getInvite())) {
            inviteUser = jslUserMapper.selectByInviteCode(reqLogin.getInvite());
        }
        JslUser jslUser = new JslUser();
        if (null != inviteUser) {
            inviteUser.setInviteNum(null != inviteUser.getInviteNum() ? inviteUser.getInviteNum() + 1 : 1);
            jslUserMapper.updateById(inviteUser);
            // 为新注册用户填写邀请人的Id
            jslUser.setInviteId(inviteUser.getUserId());
        }
        else {
            throw new JiuLuException(ConstantCode.PARAM_EXCEPTION.getCode(),"邀请人错误,请重新填写");
        }

        jslUser.setUserPhone(reqLogin.getMobile());
        jslUser.setCreateTime(CommonUtil.getCurrentDateTime());
        // 配置用户昵称
        jslUser.setNickName(RandomNameTool.getName(Language.zh, 0));
        // 默认注册账户不锁定
        jslUser.setInviteNum(0L);
        // 默认注册账户不锁定
//        jslUser.setIsLock(0);
        jslUser.setLevel(0);
        jslUser.setCompanyName(reqLogin.getCompanyName());
//        jslUser.setSiteArea(reqLogin.getSiteArea());  //去掉厂区
        jslUser.setInviteCode(reqLogin.getInvitecode());
        jslUser.setPassword(passwordEncoder.encode(jslUser.getUserPhone() + jslUser.getUserId() + jslUser.getNickName()));
        String a=jslUser.getUserPhone() + jslUser.getUserId() + jslUser.getNickName();
        jslUser.setPassword(passwordEncoder.encode(a));
        jslUser.setUserId(jslUserMapper.selectNewUser().getUserId()+1);
        return jslUserMapper.insert(jslUser) > 0;
    }

    /**
     * selectByUserPhone: 通过当前的手机号码获取用户信息<br/>
     *
     * @param
     * @return
     * @author Kai.Wang
     * @date 2021/11/1 14:42
     */
    @Override
    public JslUser selectByUserPhone(String userPhone) {
        return jslUserMapper.selectByUserPhone(userPhone);
    }

    @Override
    public JslUser selectByUserPhoneAndLevle(String userPhone, Integer level) {
        return jslUserMapper.selectByUserPhoneAndLevel(userPhone,level);
    }

    @Override
    public String checkPhone(String phone) {
        return jslUserMapper.checkPhone(phone);
    }

    @Override
    public List<UserInfoVo> selectUserByInvite(String inviteCode) {
        return jslUserMapper.selectuserByInvite(inviteCode);
    }

    /**
     * getUserInfoVoListByInviteId: 根据当前用户的Id获取被邀请人列表<br/>
     *
     * @param userId
     * @return
     * @author Jason.Wang
     * @date 2021/12/5 15:02
     */
    @Override
    public List<UserInfoVo> getUserInfoVoListByInviteId(Long userId) {
        return jslUserMapper.getUserInfoVoListByInviteId(userId);
    }

    @Override
    public BigDecimal selectMoneyByUserId(Long userId) {
        return jslUserMapper.selectMoneyByUserId(userId);
    }

    @Override
    public InviteUserInfoVo selectUserByInviteCode(String inviteCode) {
        return jslUserMapper.selectUserByInviteCode(inviteCode);
    }

    @Override
    public void setInviteUser(SetInviteUse setInviteUse, Long userId) {
        jslUserMapper.setuserInviteUser(setInviteUse.getInviteUserId(), userId);
        jslUserMapper.updateInviteNum(setInviteUse.getInviteUserId());
    }

    /**
     * 获取代理人的客户
     * @param userId 代理id
     * @param type 类型：1一级代理 2.二级代理 3.一级代理客户 4.二级代理客户 5.代理客户
     * @return
     */
    public List<Long> getTwoUsers(Long userId,Integer type){
        List<Long> result=new ArrayList<>();
        //所有用户
//        List<JslUser> jslUsers = jslUserMapper.selectList(new QueryWrapper<JslUser>());
        List<JslUserSaleInfoVo> jslUserSaleInfoVos = jslUserMapper.selectUserAndSaleInfo(userId);

        //一级代理
        List<JslUserSaleInfoVo> one = jslUserSaleInfoVos.stream().filter(e -> e.getInviteId()!=null&&e.getInviteId().equals(userId) && e.getLevel() == 1).collect(Collectors.toList());
        List<Long> oneUserIds = one.stream().map(JslUserSaleInfoVo::getUserId).collect(Collectors.toList());
        //二级代理
        List<JslUserSaleInfoVo> two = jslUserSaleInfoVos.stream().filter(e -> e.getInviteId()!=null&&oneUserIds.contains(e.getInviteId()) && e.getLevel() == 1).collect(Collectors.toList());
        List<Long> twoUserIds = two.stream().map(JslUserSaleInfoVo::getUserId).collect(Collectors.toList());

        //一级代理客户
        List<JslUserSaleInfoVo> oneClient = jslUserSaleInfoVos.stream().filter(e -> e.getInviteId()!=null&&oneUserIds.contains(e.getInviteId()) && e.getLevel() == 0).collect(Collectors.toList());
        //二级代理客户
        List<JslUserSaleInfoVo> twoClient = jslUserSaleInfoVos.stream().filter(e -> e.getInviteId()!=null&&twoUserIds.contains(e.getInviteId()) && e.getLevel() == 0).collect(Collectors.toList());

        //代理客户
        List<JslUserSaleInfoVo> client = jslUserSaleInfoVos.stream().filter(e -> e.getInviteId() != null && e.getInviteId().equals(userId) && e.getLevel() == 0).collect(Collectors.toList());
        List<Long> clientIds = client.stream().map(JslUserSaleInfoVo::getUserId).collect(Collectors.toList());

        switch (type){
            case 1:
                result=oneUserIds;
                break;
            case 2:
                result=twoUserIds;
                break;
            case 3:
                result=oneClient.stream().map(JslUserSaleInfoVo::getUserId).collect(Collectors.toList());
                break;
            case 4:
                result=twoClient.stream().map(JslUserSaleInfoVo::getUserId).collect(Collectors.toList());
                break;
            case 5:
                result=clientIds;

        }
        return result;
    }

    @Override
    public PageInfo<CustomManagerVo> customManager(CustomManagerByUserId customManagerByUserId,Integer page,Integer pageSize) {
        Long userId = customManagerByUserId.getUserId();

        Map<Long, CustomManagerVo> map = new HashMap<>();

        Long loginUserId = Objects.requireNonNull(BaseController.getUser()).getUserId();

        //他的客户详情
        List<JslShareProfitRecord> jslShareProfitRecords = jslShareProfitRecordMapper.selectList(new QueryWrapper<JslShareProfitRecord>().lambda()
                .eq(JslShareProfitRecord::getLevel, 1)
                .eq(JslShareProfitRecord::getTwoCreate, userId)
                .eq(JslShareProfitRecord::getUserId,loginUserId));

        map=getJslShareProfitRecordMap(jslShareProfitRecords,map,5);
        map=getJslShareProfitRecordMapNoThing(userId,map,5);


        PageInfo<CustomManagerVo> pageInfo = new PageInfo<>(new ArrayList<>(map.values()));
        pageInfo.setTotal(map.size());
        return pageInfo;
    }

    @Override
    public PageInfo<CustomManagerVo> customManager1(CustomManagerByUserId customManagerByUserId, Integer page, Integer pageSize) {
        Long userId = customManagerByUserId.getUserId();

        Map<Long, CustomManagerVo> map = new HashMap<>();

        Long loginUserId = Objects.requireNonNull(BaseController.getUser()).getUserId();

        //他的客户详情 一级代理下的佣金
        List<JslShareProfitRecord> jslShareProfitRecords = jslShareProfitRecordMapper.selectList(new QueryWrapper<JslShareProfitRecord>().lambda()
                .eq(JslShareProfitRecord::getLevel, 1)
                .eq(JslShareProfitRecord::getUserId,loginUserId));

        //他的客户详情 二级代理下的佣金
        List<JslShareProfitRecord> jslShareProfitRecords1 = jslShareProfitRecordMapper.selectList(new QueryWrapper<JslShareProfitRecord>().lambda()
                .eq(JslShareProfitRecord::getLevel, 0)
                .eq(JslShareProfitRecord::getUserId,loginUserId));

        map=getJslShareProfitRecordMap(jslShareProfitRecords,map,1);
        map=getJslShareProfitRecordMap(jslShareProfitRecords1,map,2);

        map=getJslShareProfitRecordMapNoThing(userId,map,1);

        map=getJslShareProfitRecordNum(map);

        PageInfo<CustomManagerVo> pageInfo = new PageInfo<>(new ArrayList<>(map.values()));
        pageInfo.setTotal(map.size());
        return pageInfo;
    }

    //type 1一级代理 2.二级代理 3.一级代理客户 4.二级代理客户 5.代理客户
    public Map<Long,CustomManagerVo> getJslShareProfitRecordMapNoThing(Long userId,Map<Long, CustomManagerVo> map,Integer type){
        List<Long> ids= getTwoUsers(userId,type);

        //将剩余没产生佣金的添加
        for (Long id : ids) {
            if (map.get(id)==null){
                JslUser jslUser = jslUserMapper.selectById(id);
                String avatar=jslUser.getAvatar()==null?"":jslUser.getAvatar();
                String name=jslUser.getCompanyName();
                if (type==1||type==2){
                    name=jslUserMapper.findSaleNameByUserId(id);
                }
                CustomManagerVo vo = new CustomManagerVo(id, name, new BigDecimal("0.00"), 0, avatar);
                vo.setCreateTime(jslUser.getCreateTime());
                map.put(id,vo);
            }
        }
        return map;
    }

    @Override
    public Map<Long, CustomManagerVo> getJslShareProfitRecordMap(List<JslShareProfitRecord> jslShareProfitRecords,Map<Long, CustomManagerVo> map,Integer type){

        //type: 1 一级佣金list 2 二级佣金list 3二级代理下的客户收益
        switch (type){
            case 1:
                for (JslShareProfitRecord dto : jslShareProfitRecords) {
                    //这一条数据的金额
                    BigDecimal money = dto.getProfitMoney();
                    //创建人
                    Long createUser = dto.getTwoCreate();
                    Long userId = dto.getTwoCreate();

                    CustomManagerVo vo = map.get(createUser);
                    if (vo!=null){
                        vo.setProfitMoney(vo.getProfitMoney().add(money));
                        map.put(createUser,vo);
                    }else {
                        JslUser jslUser = jslUserMapper.selectById(userId);
                        System.err.println(userId);
                        if(userId!=null){
                            String name = jslUserMapper.findSaleNameByUserId(userId);
                            System.err.println(name);
                            String avatar=jslUser.getAvatar()==null?"":jslUser.getAvatar();
                            map.put(createUser,new CustomManagerVo(jslUser.getUserId(),name,money,0,avatar));
                        }
                    }
                }
                break;
            case 2:
                for (JslShareProfitRecord dto : jslShareProfitRecords) {
                    //这一条数据的金额
                    BigDecimal money = dto.getProfitMoney();
                    //创建人
                    Long createUser = dto.getThrCreate();

                    CustomManagerVo vo = map.get(createUser);
                    if (vo!=null){
                        vo.setProfitMoney(vo.getProfitMoney().add(money));
                        map.put(createUser,vo);
                    }else {
                        JslUser jslUser = jslUserMapper.selectById(createUser);
                        if(createUser!=null){
                            String avatar=jslUser.getAvatar()==null?"":jslUser.getAvatar();
                            String name = jslUserMapper.findSaleNameByUserId(createUser);
                            map.put(createUser,new CustomManagerVo(jslUser.getUserId(),name,money,0,avatar));
                        }
                    }
                }
                break;

            case 3:
                for (JslShareProfitRecord dto : jslShareProfitRecords) {
                    //这一条数据的金额
                    BigDecimal money = dto.getProfitMoney();
                    //创建人
                    Long createUser = dto.getThrCreate();
                    Long userId = dto.getCreateUser();

                    CustomManagerVo vo = map.get(userId);
                    if (vo!=null){
                        vo.setProfitMoney(vo.getProfitMoney().add(money));
                        map.put(userId,vo);
                    }else {
                        JslUser jslUser = jslUserMapper.selectById(userId);
                        if(userId!=null){
                            String avatar=jslUser.getAvatar()==null?"":jslUser.getAvatar();
                            map.put(userId,new CustomManagerVo(jslUser.getUserId(),jslUser.getCompanyName(),money,0,avatar));
                        }
                    }
                }
                break;

            case 4:
                for (JslShareProfitRecord dto : jslShareProfitRecords) {
                    //这一条数据的金额
                    BigDecimal money = dto.getProfitMoney();
                    //创建人
                    Long createUser = dto.getThrCreate();

                    CustomManagerVo vo = map.get(createUser);
                    if (vo!=null){
                        vo.setProfitMoney(vo.getProfitMoney().add(money));
                        map.put(createUser,vo);
                    }else {
                        JslUser jslUser = jslUserMapper.selectById(createUser);
                        if(createUser!=null){
                            String avatar=jslUser.getAvatar()==null?"":jslUser.getAvatar();
                            map.put(createUser,new CustomManagerVo(jslUser.getUserId(),jslUser.getCompanyName(),money,0,avatar));
                        }
                    }
                }
                break;
            case 5:
                for (JslShareProfitRecord dto : jslShareProfitRecords) {
                    //这一条数据的金额
                    BigDecimal money = dto.getProfitMoney();
                    //创建人
                    Long createUser = dto.getCreateUser();

                    CustomManagerVo vo = map.get(createUser);
                    if (vo!=null){
                        vo.setProfitMoney(vo.getProfitMoney().add(money));
                        map.put(createUser,vo);
                    }else {
                        JslUser jslUser = jslUserMapper.selectById(createUser);
                        if (createUser != null) {
                            String avatar = jslUser.getAvatar() == null ? "" : jslUser.getAvatar();
                            map.put(createUser, new CustomManagerVo(jslUser.getUserId(), jslUser.getCompanyName(), money, 0, avatar));
                        }
                    }
                }
                break;


            case 6:
                for (JslShareProfitRecord dto : jslShareProfitRecords) {
                    //这一条数据的金额
                    BigDecimal money = dto.getProfitMoney();
                    //创建人
//                    Long createUser = dto.getThrCreate();
                    Long userId = dto.getTwoCreate();

                    CustomManagerVo vo = map.get(userId);
                    if (vo!=null){
                        vo.setProfitMoney(vo.getProfitMoney().add(money));
                        map.put(userId,vo);
                    }else {
                        JslUser jslUser = jslUserMapper.selectById(userId);
                        if(userId!=null){
                            String name = jslUserMapper.findSaleNameByUserId(userId);
                            String avatar=jslUser.getAvatar()==null?"":jslUser.getAvatar();
                            map.put(userId,new CustomManagerVo(jslUser.getUserId(),name,money,0,avatar));
                        }
                    }
                }
                break;

            case 7:
                for (JslShareProfitRecord dto : jslShareProfitRecords) {
                    BigDecimal money = dto.getProfitMoney();
                    Long userId = dto.getCreateUser();

                    CustomManagerVo vo = map.get(userId);
                    if (vo!=null){
                        vo.setProfitMoney(vo.getProfitMoney().add(money));
                        map.put(userId,vo);
                    }else {
                        JslUser jslUser = jslUserMapper.selectById(userId);
                        if(userId!=null){
                            String avatar=jslUser.getAvatar()==null?"":jslUser.getAvatar();
                            map.put(userId,new CustomManagerVo(jslUser.getUserId(),jslUser.getCompanyName(),money,0,avatar));
                        }
                    }
                }
                break;

        }


        return map;
    }

    @Override
    public Map<Long, CustomManagerVo> getJslShareProfitRecordNum(Map<Long, CustomManagerVo> map) {
        List<JslUser> list = this.list();
        for (Long userId : map.keySet()) {
            CustomManagerVo vo = map.get(userId);
            int size = (int) list.stream().filter(e -> e.getInviteId() != null && e.getInviteId().equals(userId) && e.getLevel() == 0).count();
            vo.setCustomNum(size);
            map.put(userId,vo);
        }

        return map;
    }


    @Override
    public CustomManagerInfoVo customManagerInfo(CustomManagerByUserId customManagerByUserId) {
        CustomManagerInfoVo customManagerInfoVo = new CustomManagerInfoVo();
        Map<Long, CustomManagerVo> map = new HashMap<>();
        List<Long> longs = new ArrayList<>();
        longs.add(customManagerByUserId.getUserId());
        PageHelper.startPage(customManagerByUserId.getPage(), customManagerByUserId.getSize());
        List<JslUser> jslUserList = jslUserMapper.selectUserByInviteId(longs);
        if (null != jslUserList && jslUserList.size() > 0) {
            for (JslUser user : jslUserList) {
                map.put(user.getUserId(), new CustomManagerVo(user.getUserId(), user.getNickName(), new BigDecimal(0), 0, user.getAvatar()));
            }
            List<Long> userIdList = jslUserList.stream().map(JslUser::getUserId).collect(Collectors.toList());
            //传这些用户有多少用户
            List<JslUser> jslUsers = jslUserMapper.selectUserByInviteId(userIdList);
            for (JslUser user : jslUsers) {
                if (map.containsKey(user.getUserId())) {
                    map.get(user.getUserId()).setCustomNum(map.get(user.getUserId()).getCustomNum() + 1);
                }

            }
            List<StatisticUserProfitMoneyVo> statisticUserProfitMoneyVos = jslShareProfitRecordMapper.statisticsUserProfitMoney(userIdList);
            for (StatisticUserProfitMoneyVo vo : statisticUserProfitMoneyVos) {
                if (map.containsKey(vo.getUserId())) {
                    map.get(vo.getUserId()).setProfitMoney(map.get(vo.getUserId()).getProfitMoney().add(vo.getProfitMoney()));
                }
            }
        }
        customManagerInfoVo.setCustomPage(new PageInfo<>(new ArrayList<>(map.values())));

        JslUser user = BaseController.getUser();

        JslUser jslUser = jslUserMapper.selectById(customManagerByUserId.getUserId());

        String nickName=jslUser.getNickName();
        if (jslUser.getLevel()==1){
            JslSaleInfo jslSaleInfo = jslSaleInfoMapper.selectOne(new QueryWrapper<JslSaleInfo>().lambda().eq(JslSaleInfo::getBindId, customManagerByUserId.getUserId()));
            if (jslSaleInfo==null){
                nickName="";
            }else{
                nickName=jslSaleInfo.getSaleName();
            }

        }

        customManagerInfoVo.setUserId(jslUser.getUserId());
        customManagerInfoVo.setNickName(nickName);
        if (StringUtils.isNotBlank(jslUser.getUserPhone())) {
            customManagerInfoVo.setMobile(jslUser.getUserPhone().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
        }
        customManagerInfoVo.setAvatar(jslUser.getAvatar());
        if (jslUser.getLevel() == 0) {
            customManagerInfoVo.setLevelName("普通用户");
        }
        if (jslUser.getLevel() == 1) {
            customManagerInfoVo.setLevelName("代理人");
        }
        if (jslUser.getLevel() == 2) {
            customManagerInfoVo.setLevelName("销售经理");
        }

        JslUserOrderTotalVo jslUserOrderTotalVo = jslOrderMapper.selectUserOrderTotal(customManagerByUserId.getUserId());
        if (null != jslUserOrderTotalVo) {
            customManagerInfoVo.setConsumptionMoney(jslUserOrderTotalVo.getConsumptionMoney());
            customManagerInfoVo.setOrderNums(jslUserOrderTotalVo.getOrderNums());
        }
        return customManagerInfoVo;
    }

    @Override
    public CustomUserAndorderInfoVo getUserMessageAndOrder(CustomManagerByUserId customManagerByUserId) {
        //1.查询用户信息
        JslUser user = jslUserMapper.selectById(customManagerByUserId.getUserId());
        CustomUserAndorderInfoVo vo = new CustomUserAndorderInfoVo();
        vo.setUserId(user.getUserId());
        vo.setNickName(user.getNickName());
        vo.setAvatar(user.getAvatar());
        if (user.getLevel() == 0) {
            vo.setLevelName("普通用户");
        }
        if (user.getLevel() == 1) {
            vo.setLevelName("业务员");
        }
        if (user.getLevel() == 2) {
            vo.setLevelName("销售经理");
        }
        JslUserOrderTotalVo jslUserOrderTotalVo = jslOrderMapper.selectUserOrderTotal(customManagerByUserId.getUserId());
        vo.setConsumptionMoney(jslUserOrderTotalVo.getConsumptionMoney());
        vo.setOrderNums(jslUserOrderTotalVo.getOrderNums());
        return null;
    }

    @Override
    public CustomUserMessageVo getCustomUserMessage(CustomManagerByUserId customManagerByUserId) {
        //1.查询用户信息
        JslUser user = jslUserMapper.selectById(customManagerByUserId.getUserId());
        CustomUserMessageVo vo = new CustomUserMessageVo();
        vo.setUserId(user.getUserId());
        vo.setNickName(user.getCompanyName());
        vo.setAvatar(user.getAvatar());
        if (user.getLevel() == 0) {
            vo.setLevelName("普通用户");
        }
        if (user.getLevel() == 1) {
            vo.setLevelName("业务员");
        }
        if (user.getLevel() == 2) {
            vo.setLevelName("销售经理");
        }
        JslUserOrderTotalVo jslUserOrderTotalVo = jslOrderMapper.selectUserOrderTotal(customManagerByUserId.getUserId());
        if (null != jslUserOrderTotalVo) {
            vo.setConsumptionMoney(jslUserOrderTotalVo.getConsumptionMoney());
            vo.setOrderNums(jslUserOrderTotalVo.getOrderNums());
        } else {
            vo.setConsumptionMoney(new BigDecimal(0));
            vo.setOrderNums(0);
        }
        return vo;
    }

    @Override
    public CommissionManagerInfoVo getCommission(Long userId) {
        List<BankCardInfoVo> bankCardInfoVos = iJslUserBankCardInfoService.selectBankCardInfoListByUserId(userId);
        JslUser jslUser = jslUserMapper.selectById(userId);
        CommissionManagerInfoVo vo = new CommissionManagerInfoVo();
        vo.setBankCardList(bankCardInfoVos);
        vo.setConsumeAmount(jslUser.getConsumeAmount());
        return vo;
    }

    @Override
    public void changePwdByPwd(ChangePwdByPwd changePwdByPwd, Long userId) throws Exception {
        String newPwd1 = new String(RsaUtil.decryptByPrivateKey(Base64.decodeBase64(changePwdByPwd.getNewPwd1()), customerApiConfig.getPrivateKey()), StandardCharsets.UTF_8);
        String newPwd2 = new String(RsaUtil.decryptByPrivateKey(Base64.decodeBase64(changePwdByPwd.getNewPwd2()), customerApiConfig.getPrivateKey()), StandardCharsets.UTF_8);
        if(!newPwd1.equals(newPwd2)){
            throw new JiuLuException(ConstantCode.PARAM_EXCEPTION.getCode(), "新密码两次不一致");
        }
        String oldPwd = new String(RsaUtil.decryptByPrivateKey(Base64.decodeBase64(changePwdByPwd.getOldPwd()), customerApiConfig.getPrivateKey()), StandardCharsets.UTF_8);
        JslUser jslUser = jslUserMapper.selectUserByPwd(userId, passwordEncoder.encode(oldPwd));
        if (null == jslUser) {
            throw new JiuLuException(ConstantCode.PARAM_EXCEPTION.getCode(), "旧密码输入错误");
        }

//        (passwordEncoder.encode(jslUser.getUserPhone() + jslUser.getUserId() + jslUser.getNickName());
        jslUser.setPassword(passwordEncoder.encode(newPwd1));
        jslUserMapper.updateById(jslUser);

    }

    @Override
    public void changePwdByPhone(ChangePwdByPhone changePwdByPhone) throws Exception {
//        JslUser jslUser = jslUserMapper.selectByUserPhone(changePwdByPhone.getMobile());
        JslUser jslUser = getCurrentUserInfo();
        if (null == jslUser) {
            throw new JiuLuException(ConstantCode.PARAM_EXCEPTION.getCode(), "当前手机号不存在");
        }
        String oldPwd = new String(RsaUtil.decryptByPrivateKey(Base64.decodeBase64(changePwdByPhone.getNewPwd1()), customerApiConfig.getPrivateKey()), StandardCharsets.UTF_8);
        jslUser.setPassword(passwordEncoder.encode(oldPwd));
        jslUserMapper.updateById(jslUser);
    }


    protected JslUser getCurrentUserInfo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication.getPrincipal().equals("anonymousUser"))
            throw new ParamException(ConstantCode.TOKEN_EXPIRE.getCode(),"token过期请重新登录");
        CustomerUserDetails userDetails = (CustomerUserDetails) authentication.getPrincipal();
        if (null != userDetails && null != userDetails.getJslUser()) {
            return userDetails.getJslUser();
        }
        return null;
    }

    @Override
    public BigDecimal getUserMoney(Long userId) {
        System.out.println(userId);
        List<JslShareProfitRecord> oneList = jslShareProfitRecordMapper.selectRecordByUserIdAndLevel(userId,1);
        List<JslShareProfitRecord> twoList = jslShareProfitRecordMapper.selectRecordByUserIdAndLevel(userId,0);
        List<JslShareProfitRecord> sumList = jslShareProfitRecordMapper.selectRecordByUserIdAndLevel(userId,2);
        BigDecimal decimal = commissionMapper.selectAmountByuserId(userId);
        //一级佣金
        BigDecimal oneAmount = sum(oneList);
        //二级佣金
        BigDecimal twoAmount = sum(twoList);
        //客户佣金
        BigDecimal sumAmount = sum(sumList);
        if(decimal ==null){
            decimal=new BigDecimal("0.00");
        }
        BigDecimal userMoney = oneAmount.add(twoAmount).add(sumAmount).subtract(decimal);
//        BigDecimal userMoney = jslUserBalanceMapper.selectMaxBalanceByUserId(userId);
//        if(userMoney==null) userMoney=new BigDecimal("0.00");
//        System.out.println(balance);
//        if(balance.compareTo(userMoney)==1) userMoney=balance;
//        userMoney=balance;
        return userMoney;
    }

    public BigDecimal sum(List<JslShareProfitRecord> list) {
        BigDecimal result = new BigDecimal("0");
        for (JslShareProfitRecord vo : list) {
            result = result.add(vo.getProfitMoney());
        }
        return result;
    }
}
